/**
 * Created by chaozhongyuan on 2018/12/25.
 */
import Layout from '../../modules/layout/Layout'
import {
  MenuComponent
} from '../../router/index'
const main = {
  generateMenu(dir, trade) {
    if (dir instanceof Array && trade instanceof Array && dir.length > 0 && trade.length > 0) {
      const map = {};
      dir.forEach(item => {
        map[item.ParentMenuNum] = [];
      })
      trade.forEach(item => {
        map[item.ParentMenuNum] = [];
      })
      listToMap(dir, map);
      listToMap(trade, map);
      const tree = map['0']
      parse(map, tree)
      tree.push({
        path: '*',
        redirect: '/404',
        hidden: true
      })
      return tree;
    } else {
      return [];
    }

    function parse(o, tree) {
      for (let i = 0; i < tree.length; i++) {
        if (o[tree[i].name]) {
          tree[i].children = o[tree[i].name];
          parse(o, tree[i].children);
        }
      }
    }

    function listToMap(list, map) {
      list.forEach(item => {
        if (item.MenuType === '02') {
          map[item.ParentMenuNum].push({
            path: item.MenuNum,
            name: item.MenuNum,
            component: MenuComponent[item.MenuPath],
            meta: {
              title: item.MenuName
            }
          })
        } else if (item.MenuType === '01' && item.ParentMenuNum !== '0') {
          map[item.ParentMenuNum].push({
            path: '/' + item.ParentMenuNum + '/' + item.MenuNum,
            name: item.MenuNum,
            alwaysShow: true,
            component: MenuComponent[item.MenuPath],
            meta: {
              title: item.MenuName,
              icon: item.MenuIcon
            }
          })
        } else if (item.MenuType === '01' && item.ParentMenuNum === '0') {
          map[item.ParentMenuNum].push({
            component: Layout,
            path: '/' + item.MenuNum,
            name: item.MenuNum,
            alwaysShow: true,
            meta: {
              title: item.MenuName,
              icon: item.MenuIcon
            }
          })
        }
      })
    }
  }
}

export default main
